from django.utils.deprecation import MiddlewareMixin
from django.core.cache import cache
from django.http.response import HttpResponseForbidden
from .urils  import get_client_ip
class IPRequestMiddleware(MiddlewareMixin):
    def process_request(self, request):
        ip = get_client_ip(request)
        key = f'ip_rate_limit_{ip}'
        count = cache.get(key, 0)

        if count >= 1000:
            return HttpResponseForbidden('请求过于频繁，请稍后再试')


        cache.set(key,count+1,60)  # 每分钟限制1000次请求
